import 'dart:typed_data';

import 'package:animated_text_kit/animated_text_kit.dart';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gongge/utils/AudioUtils.dart';
import '../config/AppConst.dart';
import '../utils/SpUtils.dart';
import '../utils/TimeUtils.dart';
import '../generated/l10n.dart';

import '../main.dart';
import '../utils/CommUtils.dart';

/**
 * 游戏结束提示文字
 */

class GameEndText extends Dialog {
  List<String> list = [];
  // int CurrentScore = 0; //当前分数
  // int HistoricalScore = 0; //历史分数
//Uint8List? gamebg; //游戏背景截图
  GameEndText({
    required this.list,
    //  required this.CurrentScore,
    //   required this.HistoricalScore,
    //  required this.gamebg,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
        type: MaterialType.transparency,
        child: Center(
            child: DefaultTextStyle(
          style: const TextStyle(
            fontSize: 25,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
          child: AnimatedTextKit(
            isRepeatingAnimation: false,
            pause: const Duration(milliseconds: 1000),
            animatedTexts: list
                .map((e) => TyperAnimatedText(
                      e,
                      textAlign: TextAlign.start,
                      speed: Duration(milliseconds: 300),
                    ))
                .toList(),
            onFinished: () {
              //会被关掉最上层的弹窗
              // Navigator.pop(context);
              //由于截图的弹窗比较耗时，所以这里直接关闭此弹窗即可
              // showDialog(
              //     context: context,
              //     // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
              //     barrierDismissible: false, //控制 Dialog 是否消失
              //     barrierLabel: "",
              //     builder: (BuildContext context) {
              //       return Dialog(
              //         backgroundColor: Colors.transparent,
              //         child: GameEndBg(
              //           currentScore: CurrentScore,
              //           historicalScore: HistoricalScore,
              //           gamebg: gamebg,
              //         ),
              //       );
              //     });
            },
            //   repeatForever: false,
          ),
        )));
  }
}

/**
 * 游戏结束带分数图片
 */
class GameEndBg extends Dialog {
  int currentScore = 0; //当前分数
  int historicalScore = 0; //历史分数
  Uint8List? gamebg; //游戏背景截图
  CallBack? callback; //点击新游戏回调
  int type; //1经典，2每日
  GameEndBg(
      {required this.currentScore,
      required this.historicalScore,
      required this.gamebg,
      required this.callback,
      required this.type});
  @override
  Widget build(BuildContext context) {
    double size = CommUtils.getWidth(context);
    double hight = CommUtils.getHeight(context);
    return Material(
      type: MaterialType.transparency,
      child: Container(
       width: CommUtils.getISWidth(size, hight)?hight*0.7:size,
        margin: EdgeInsets.only(top: hight * 0.1),

        child: Stack(
          children: [
            getBg(context,size,hight),
            //头部图片
            Stack(
              children: [
                Image.asset('assets/images/game_end_top.png',
                    //  height: ScreenUtil().setWidth(126),
                    width: double.infinity,
                    fit: BoxFit.fitWidth),
                Align(
                  alignment: Alignment.topCenter,
                  //标题
                  child: Container(
                    height: hight * 0.08,
                    margin: EdgeInsets.only(top: hight * 0.08),
                    child: Center(
                      child: CommUtils.getStroke2(getTopText(context), 25,
                          Color(0xffffde50), Color(0Xff313175), 5, 2),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  String getTopText(BuildContext context) {
    if (type == 1) {
      var weekScore = SpUtils.getInstance()?.getInt(AppConst.weekScore);
      var monthScore = SpUtils.getInstance()?.getInt(AppConst.monthScore);
      var lastScoreTime =
          SpUtils?.getInstance()?.getInt(AppConst.lastScoreTime);

      bool isMoreThan = false; //true超过今日最佳；
      if (lastScoreTime != 0) {
        //上次有保留的分数时间搓
        //1.查询当前时间是否在本月
        var lastTime = TimeUtils.gtTime(
            DateTime.fromMillisecondsSinceEpoch(lastScoreTime!));

        var nowTime = TimeUtils.gtTime(DateTime.now());
        if (nowTime != lastTime) {
          print("不在当月了");
          //上次获取的分数已经不在本月了
          monthScore = 0;
        }
        //2.查询是否在本周
        if (!TimeUtils.IsBetweenOneWeek(lastScoreTime)) {
          //不在本周了
          weekScore = 0;
        }

        //今天

        if (TimeUtils.gtTime6(DateTime.now()) ==
            TimeUtils.gtTime6(
                DateTime.fromMillisecondsSinceEpoch(lastScoreTime))) {
          //上次保存的在今天
          var todayScore = SpUtils.getInstance()?.getInt(AppConst.todayScore);
          if (currentScore > todayScore!) {
            isMoreThan = true;
            //超过今日最佳
            SpUtils.getInstance()?.setInt(AppConst.todayScore, currentScore);
          }
        } else {
          //不再一天了
          SpUtils.getInstance()?.setInt(AppConst.todayScore, currentScore);
        }

        // 今年
        if (DateTime.now().year ==
            DateTime.fromMillisecondsSinceEpoch(lastScoreTime).year) {
          //上次保存的在今天
          var yearScore = SpUtils.getInstance()?.getInt(AppConst.yearScore);
          if (currentScore > yearScore!) {
            //超过今年最佳
            SpUtils.getInstance()?.setInt(AppConst.yearScore, currentScore);
          }
        } else {
          //不再是今年
          SpUtils.getInstance()?.setInt(AppConst.yearScore, currentScore);
        }
      } else {
        isMoreThan = true;
        SpUtils.getInstance()?.setInt(AppConst.todayScore, currentScore);
        SpUtils.getInstance()?.setInt(AppConst.weekScore, currentScore);
        SpUtils.getInstance()?.setInt(AppConst.monthScore, currentScore);
        SpUtils.getInstance()?.setInt(AppConst.yearScore, currentScore);
      }

      //存入本次分数的时间搓。
      SpUtils?.getInstance()?.setInt(
          AppConst.lastScoreTime, DateTime.now().millisecondsSinceEpoch);

      if (isMoreThan && currentScore < historicalScore) {
        //超过今日最佳
        AudioUtils.getInstance()?.play2("classic_to_today.mp3");
      }

      if (currentScore > historicalScore) {
        AudioUtils.getInstance()?.play2("classic_hight_sore.mp3");
        historicalScore = currentScore;
        SpUtils?.getInstance()?.setInt(AppConst.historyScore, currentScore);
        return S.of(context).history_hight;
      } else if (currentScore > monthScore!) {
        AudioUtils.getInstance()?.play2("classic_hight_sore.mp3");
        SpUtils.getInstance()?.setInt(AppConst.monthScore, currentScore);
        return S.of(context).month_history;
      } else if (currentScore > weekScore!) {
        AudioUtils.getInstance()?.play2("classic_hight_sore.mp3");
        SpUtils.getInstance()?.setInt(AppConst.weekScore, currentScore);
        return S.of(context).week_history;
      } else {
        AudioUtils.getInstance()?.play2("classic_ordinary.mp3");
        return S.of(context).ongratulations_;
      }
    } else {
      AudioUtils.getInstance()?.play2("challenge_complete.mp3");
      //每日挑战 完成
      return S.of(context).finish_daily;
    }
  }

  Widget getBg(BuildContext context, double size,  double hight) {
    
    return Column(
      children: [
         SizedBox(height: hight*0.1)  ,
        Container(
          width: double.infinity,
            margin: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15)),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/bg_seting.png'),
                  fit: BoxFit.contain),
            ),
            child: Padding(
              padding: EdgeInsets.only( 
                //不要设左右边距，否则web宽度变化，中间的框框会跟着变化
                  top: hight * 0.09,
                  bottom: hight* 0.08),
              child: Column(
                children: [
                  
                getTypeText(context,hight),

                  Container(
                    width: CommUtils.getISWidth(size, hight)?hight*0.42:size*0.65,
                    height: hight * 0.4,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage('assets/images/middle.png'),
                          fit: BoxFit.fill),
                    ),
                  child: gamebg != null ? Image.memory(gamebg!) : Text(""),
                    
                  ),

                  SizedBox(
                    height: hight * 0.02,
                  ),

                  //新游戏按钮
                  GestureDetector(
                      onTap: () {
                        //因为有两个弹窗，
                        Navigator.pop(context);
                        Navigator.pop(context);
                        if (type == 1) {
                          callback?.call(historicalScore);
                        } else if (type == 2) {
                          //每日挑战成功关闭界面 首页刷新
                          Navigator.pop(context, 1);
                        }
                      },
                      child: Padding(
                        padding: EdgeInsets.only(
                            left: hight * 0.15,
                            right: hight * 0.15),
                        child: getOnclick(context, hight),
                      )),
                ],
              ),
            )),
      ],
    );
  }

  Widget getOnclick(BuildContext context, double hight) {
    if (type == 1) {
      return Container(
          height: hight * 0.07,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/new_game.png'),
              fit: BoxFit.contain,
            ),
          ),
          alignment: Alignment.center,
          child: Padding(
              padding: EdgeInsets.only(top: 5, bottom: 5, right: 5, left: 5),
              child: CommUtils.getTextGame(
                context,
                15,
                S.current.new_game,
                Color(0xffe7f9c6),
                Color(0Xff5afddd),
              )));
    } else {
      //每日
      return Container(
        height: hight * 0.06,
        child:
            Image.asset('assets/images/button_back.png', fit: BoxFit.contain),
      );
    }
  }

  Widget getTypeText(BuildContext context,double height) {
    if (type == 1) {
      //经典
      return Column(
        children: [
          CommUtils.getTextString(
              context, S.of(context).fraction1, 15, false, 1, Colors.white),
          SizedBox(
            height: 6,
          ),
          CommUtils.getTextString(
              context, "${currentScore}", 20, true, 1, Colors.white),
        ],
      );
    } else {
      //每日挑战，
     
       return SizedBox(
        height: height*0.05,
       );
    }
  }
}
